<?php

namespace App\Api\Controllers\Admin;

use App\Api\Requests\AdminMenuRequest;
use App\Api\Traits\Tree;
use App\Models\AdminMenu;
use App\Models\AdminRole;
use Illuminate\Http\Request;

class AdminMenuController extends Controller
{
    use Tree;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $datas = AdminMenu::query()
            ->orderBy('parent_id')
            ->orderBy('sort')
            ->get();

        foreach ($datas as $key => $data) {
            $datas[$key]['roleIdArr'] = array_column($data->roles->toArray(), 'id');
        }

        $datas = $this->formatTree($datas->toArray());

        // 角色列表
        $roleList = AdminRole::fetchRoles();

        return $this->success([
            'list' => $datas,
            'roleList' => $roleList,
        ]);
    }

    /**
     * @param AdminMenuRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(AdminMenuRequest $request)
    {
        $request->validated();
        $row = new AdminMenu($request->all());
        $row->save();
        $row->addRoles($request->input('roleIdArr'), $row);

        return $this->success($request->all(), '数据创建成功');
    }

    /**
     * @param AdminMenuRequest $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(AdminMenuRequest $request, $id)
    {
        $row = AdminMenu::find($id);
        $request->validated();
        $row->update($request->all());
        $row->addRoles($request->input('roleIdArr'), $row);

        return $this->success($row->toArray(), '数据更新成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (empty($id)) {
            return $this->error('请求处理失败，参数错误。');
        }

        $idArr  = explode(',', $id);
        $result = AdminMenu::destroy($idArr);

        return $this->success([$idArr], "成功处理 {$result} 条数据。");
    }
}
